package top.littlejiang.onlinexam.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import top.littlejiang.onlinexam.common.base.LoginException;
import top.littlejiang.onlinexam.common.utils.*;
import top.littlejiang.onlinexam.entity.OlexamUser;
import top.littlejiang.onlinexam.service.OlexamLoginService;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chen
 * @Description
 * @since 2021/1/2 11:50
 */
@Service
public class OlexamLoginServiceImpl implements OlexamLoginService {
    public static String LOGIN_SERVICE = "from_login_service";

    /**
     * @param codeId
     * @return String 验证码图片 base64
     * @Description 获取 验证码图片 先删除之前的，再获取新的
     * @author chen
     * @since 2021/1/2 11:54
     */
    @Override
    public String getValiCode(String codeId) {
        RedisUtils.delKey(codeId);
        ValidateCode code = new ValidateCode();
        Map<String,String> map = code.create();
        RedisUtils.setex(codeId, RedisUtils.CODE_TIME, map.get("codeText"));
        return map.get("codeImage");
    }

    /**
     *  验证密码是否正确
     * @param userPwd 正确密码
     * @param userSalty 用户盐值（查库）
     * @param password 前端传入的密码输入值
     * @return boolean
     * @author chen
     * @since 2021/1/3 14:11
     */
    @Override
    public void checkPwd(String userPwd, String userSalty, String password) {
        String toCheck = PasswordUtils.md5SaltyAndPwd(userSalty, password);
        if(!toCheck.equals(userPwd)){
            throw new LoginException("用户名或密码错误!");
        }
    }

    /**
     * 检查验证码是否正确
     *
     * @param inputCode
     * @param codeUuid
     * @return
     */
    @Override
    public void checkValideCode(String inputCode, String codeUuid) {
        String codeId = RedisUtils.CODE_PREFIX + codeUuid;
        String correctCode = RedisUtils.getStr(codeId);

        if (StringUtils.isEmpty(correctCode)){
            throw new LoginException("验证码已过期！");
        }
        // 验证码作废
        RedisUtils.delKey(codeId);

        if((correctCode.toLowerCase()).equals(inputCode) == false){
            throw new LoginException("验证码错误！");
        }
    }

    /**
     * 登录成功在redis保存登录信息
     *
     * @param olexamUser
     */
    @Override
    public void addLoginInfo(OlexamUser olexamUser) {
        Map<String,String> userinfo = new HashMap<>(5);
        userinfo.put("sessionId",HttpContextUtils.getHttpServletRequest().getSession().getId());
        userinfo.put("ip",IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest()));
        userinfo.put("examId","0");
        userinfo.put("roleSign",olexamUser.getRoleSign());
        RedisUtils.hmset(RedisUtils.LOGIN_PREFIX + olexamUser.getId().toString(),userinfo);
    }
}
